import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, message, Card, Space, Popconfirm, Badge, List, Form, Input, InputNumber, DatePicker } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { LoadingOutlined, UserOutlined, CalendarOutlined } from '@ant-design/icons';
import axios from 'axios';
import moment from 'moment';

interface Club {
  id: number;
  name: string;
  description: string;
  type: string;
  president: string;
  created_at: string;
  memberCount?: number;
}

interface Application {
  id: number;
  student_id: number;
  club_id: number;
  status: string;
  created_at: string;
  student_name: string;
  student_no: string;
  gender: string;
}

interface Member {
  id: number;
  student_id: number;
  club_id: number;
  status: string;
  created_at: string;
  student_name: string;
  student_no: string;
  gender: string;
}

interface Activity {
  id: number;
  title: string;
  type: string;
  description: string;
  location: string;
  start_time: string;
  end_time: string;
  points: number;
  max_participants: number;
  signup_deadline: string;
  club_id: number;
}

interface RegisteredStudent {
  id: number;
  student_id: number;
  register_time: string;
  student_name: string;
  student_no: string;
}

const ManageClub: React.FC = () => {
  // 状态管理
  const [clubs, setClubs] = useState<Club[]>([]);                    // 社团列表
  const [loading, setLoading] = useState<boolean>(false);            // 加载状态
  const [applications, setApplications] = useState<Application[]>([]);// 申请列表
  const [members, setMembers] = useState<Member[]>([]);              // 成员列表
  const [isApplicationModalVisible, setIsApplicationModalVisible] = useState<boolean>(false);  // 申请模态框显示状态
  const [isMembersModalVisible, setIsMembersModalVisible] = useState<boolean>(false);         // 成员模态框显示状态
  const [selectedClubId, setSelectedClubId] = useState<number | null>(null);                  // 选中的社团ID
  const [selectedClubName, setSelectedClubName] = useState<string>('');                       // 选中的社团名称
  const [applicationsLoading, setApplicationsLoading] = useState<boolean>(false);             // 申请列表加载状态
  const [membersLoading, setMembersLoading] = useState<boolean>(false);                       // 成员列表加载状态
  const [activities, setActivities] = useState<Activity[]>([]);
  const [selectedActivity, setSelectedActivity] = useState<Activity | null>(null);
  const [isActivityModalVisible, setIsActivityModalVisible] = useState(false);
  const [isUpdateModalVisible, setIsUpdateModalVisible] = useState(false);
  const [isCreateModalVisible, setIsCreateModalVisible] = useState(false);
  const [isRegisteredStudentsModalVisible, setIsRegisteredStudentsModalVisible] = useState(false);
  const [registeredStudents, setRegisteredStudents] = useState<RegisteredStudent[]>([]);
  const [registeredStudentsLoading, setRegisteredStudentsLoading] = useState(false);
  const [activitySignInCodes, setActivitySignInCodes] = useState<{[activityId: number]: string | null}>({}); // 新增状态：存储活动签到码
  const [signInCodeModalVisible, setSignInCodeModalVisible] = useState(false); // 新增状态：控制签到码模态框显示
  const [currentActivitySignInCode, setCurrentActivitySignInCode] = useState<string | null>(null); // 新增状态：当前显示的签到码

  // 在组件加载时从 localStorage 读取签到码
  useEffect(() => {
    const savedCodes = localStorage.getItem('activitySignInCodes');
    if (savedCodes) {
      try {
        setActivitySignInCodes(JSON.parse(savedCodes));
      } catch (error) {
        console.error('Failed to parse activity sign-in codes from localStorage:', error);
        // 清除无效的 localStorage 数据
        localStorage.removeItem('activitySignInCodes');
      }
    }
  }, []); // 空依赖数组，只在组件挂载时运行一次

  // 获取社团列表
  const fetchClubs = async () => {
    setLoading(true);
    try {
      const userInfo = localStorage.getItem('userInfo');
      if (!userInfo) {
        message.error('请先登录');
        return;
      }

      const { name } = JSON.parse(userInfo);
      const response = await axios.get(`http://localhost:5000/api/president/${name}`);
      
      if (response.data.success) {
        const clubsData = response.data.data;
        
        // 获取每个社团的成员数量
        const clubsWithMemberCount = await Promise.all(
          clubsData.map(async (club: Club) => {
            try {
              const countResponse = await axios.get(`http://localhost:5000/api/studentClubs/count/approved/${club.id}`);
              return {
                ...club,
                memberCount: countResponse.data.approvedCount
              };
            } catch (error) {
              console.error(`获取社团 ${club.id} 成员数量失败:`, error);
              return {
                ...club,
                memberCount: 0
              };
            }
          })
        );
        
        setClubs(clubsWithMemberCount);
      } else {
        message.error('获取社团列表失败');
      }
    } catch (error) {
      console.error('获取社团列表失败:', error);
      message.error('获取社团列表失败');
    } finally {
      setLoading(false);
    }
  };

   // 获取申请列表
  const fetchApplications = async (clubId: number) => {
    setApplicationsLoading(true);
    try {
      const response = await axios.get(`http://localhost:5000/api/studentClubs/status/pending/club/${clubId}`);
      
      // 获取每个申请的学生信息
      const applicationsWithStudentInfo = await Promise.all(
        response.data.map(async (application: Application) => {
          try {
            const studentResponse = await axios.get(`http://localhost:5000/api/getStudentById/${application.student_id}`);
            return {
              ...application,
              student_name: studentResponse.data.data.name,
              student_no: studentResponse.data.data.student_no,
              gender: studentResponse.data.data.gender
            };
          } catch (error) {
            console.error('获取学生信息失败:', error);
            return {
              ...application,
              student_name: '未知',
              student_no: '未知',
              gender: '未知'
            };
          }
        })
      );
      
      setApplications(applicationsWithStudentInfo);
    } catch (error) {
      console.error('获取申请列表失败:', error);
      message.error('获取申请列表失败');
    } finally {
      setApplicationsLoading(false);
    }
  };

  const fetchMembers = async (clubId: number) => {
    setMembersLoading(true);
    try {
      const response = await axios.get(`http://localhost:5000/api/studentClubs/status/approved/club/${clubId}`);
      
      // 获取每个成员的学生信息
      const membersWithStudentInfo = await Promise.all(
        response.data.map(async (member: Member) => {
          try {
            const studentResponse = await axios.get(`http://localhost:5000/api/getStudentById/${member.student_id}`);
            return {
              ...member,
              student_name: studentResponse.data.data.name,
              student_no: studentResponse.data.data.student_no,
              gender: studentResponse.data.data.gender
            };
          } catch (error) {
            console.error('获取学生信息失败:', error);
            return {
              ...member,
              student_name: '未知',
              student_no: '未知',
              gender: '未知'
            };
          }
        })
      );
      
      setMembers(membersWithStudentInfo);
    } catch (error) {
      console.error('获取成员列表失败:', error);
      message.error('获取成员列表失败');
    } finally {
      setMembersLoading(false);
    }
  };

  const handleViewApplications = (clubId: number) => {
    setSelectedClubId(clubId);
    setIsApplicationModalVisible(true);
    fetchApplications(clubId);
  };

  const handleViewMembers = (clubId: number, clubName: string) => {
    setSelectedClubId(clubId);
    setSelectedClubName(clubName);
    setIsMembersModalVisible(true);
    fetchMembers(clubId);
  };

  const handleApplicationStatus = async (applicationId: number, status: 'approved' | 'rejected') => {
    try {
      const response = await axios.put(`http://localhost:5000/api/putSclubById/${applicationId}`, {
        status
      });

      if (response.data.message === '根据ID更新成功') {
        message.success(`已${status === 'approved' ? '通过' : '拒绝'}申请`);
        fetchApplications(selectedClubId!);
        // 刷新社团列表以更新成员数量
        fetchClubs();
      } else {
        message.error('处理申请失败');
      }
    } catch (error) {
      console.error('处理申请失败:', error);
      message.error('处理申请失败');
    }
  };

  const handleRemoveMember = async (studentId: number, clubId: number) => {
    try {
      const response = await axios.delete('http://localhost:5000/api/delectSClub', {
        data: {
          student_id: studentId,
          club_id: clubId
        }
      });
      
      if (response.status === 200) {
        message.success('成功移除成员');
        fetchMembers(clubId);
        // 刷新社团列表以更新成员数量
        fetchClubs();
      } else {
        message.error('移除成员失败');
      }
    } catch (error) {
      console.error('移除成员失败:', error);
      message.error('移除成员失败，请稍后重试');
    }
  };

  const fetchActivities = async (clubId: number) => {
    try {
      const response = await axios.get(`http://localhost:5000/api/activity/${clubId}`);
      if (response.data.success) {
        setActivities(response.data.data);
      }
    } catch (error) {
      message.error('获取活动信息失败');
    }
  };

  const handleUpdateActivity = async (values: any) => {
    try {
      // 格式化日期时间为 ISO 8601
      const formattedValues = {
        ...values,
        // Use ISO 8601 format for better compatibility
        start_time: values.start_time.toISOString(),
        end_time: values.end_time.toISOString(),
        signup_deadline: values.signup_deadline.toISOString(),
      };

      const response = await axios.put(`http://localhost:5000/api/updateActivities/${selectedActivity?.id}`, formattedValues);
      if (response.data.success) {
        message.success('更新活动成功');
        setIsUpdateModalVisible(false);
        fetchActivities(selectedActivity?.club_id || 0);
      }
    } catch (error) {
      message.error('更新活动失败');
    }
  };

  const handleCreateActivity = async (values: any) => {
    try {
      // 格式化日期时间
      const formattedValues = {
        ...values,
        // Use ISO 8601 format for better compatibility
        start_time: values.start_time.toISOString(),
        end_time: values.end_time.toISOString(),
        signup_deadline: values.signup_deadline.toISOString(),
        club_id: selectedClubId
      };

      const response = await axios.post('http://localhost:5000/api/createActivities', formattedValues);
      if (response.data.success) {
        message.success('创建活动成功');
        setIsCreateModalVisible(false);
        fetchActivities(selectedClubId!);
      }
    } catch (error: any) {
      console.error('创建活动失败:', error.response?.data || error);
      message.error(error.response?.data?.message || '创建活动失败');
    }
  };

  const fetchRegisteredStudents = async (activityId: number) => {
    setRegisteredStudentsLoading(true);
    try {
      const response = await axios.get(`http://localhost:5000/api/activityIdregistered/${activityId}`);
      if (response.data.success) {
        // 获取每个学生的详细信息
        const studentsWithDetails = await Promise.all(
          response.data.data.records.map(async (record: any) => {
            try {
              const studentResponse = await axios.get(`http://localhost:5000/api/getStudentById/${record.student_id}`);
              return {
                ...record,
                student_name: studentResponse.data.data.name,
                student_no: studentResponse.data.data.student_no
              };
            } catch (error) {
              console.error('获取学生信息失败:', error);
              return {
                ...record,
                student_name: '未知',
                student_no: '未知'
              };
            }
          })
        );
        setRegisteredStudents(studentsWithDetails);
      }
    } catch (error) {
      console.error('获取报名学生信息失败:', error);
      message.error('获取报名学生信息失败');
    } finally {
      setRegisteredStudentsLoading(false);
    }
  };

  // 生成四位随机签到码并保存到 localStorage
  const generateSignInCode = (activityId: number) => {
    const code = Math.floor(1000 + Math.random() * 9000).toString();
    
    // 更新状态
    const updatedCodes = {
      ...activitySignInCodes,
      [activityId]: code
    };
    setActivitySignInCodes(updatedCodes);
    
    // 保存到 localStorage
    try {
      localStorage.setItem('activitySignInCodes', JSON.stringify(updatedCodes));
    } catch (error) {
      console.error('Failed to save activity sign-in code to localStorage:', error);
      message.error('保存签到码到本地存储失败');
    }

    setCurrentActivitySignInCode(code);
    setSignInCodeModalVisible(true);
  };

  const clubColumns: ColumnsType<Club> = [
    {
      title: '社团ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      align: 'center',
    },
    {
      title: '社团名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '社团描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '成员数量',
      dataIndex: 'memberCount',
      key: 'memberCount',
      width: 100,
      align: 'center',
      render: (count: number, record) => (
        <Button 
          type="link" 
          onClick={() => handleViewMembers(record.id, record.name)}
        >
          <Badge count={count} showZero>
            <UserOutlined style={{ fontSize: 16 }} />
          </Badge>
        </Button>
      ),
    },
    {
      title: '社团活动',
      key: 'activities',
      width: 100,
      align: 'center',
      render: (_, record) => (
        <Button 
          type="link" 
          onClick={() => {
            setSelectedClubId(record.id);
            setSelectedClubName(record.name);
            fetchActivities(record.id);
            setIsActivityModalVisible(true);
          }}
        >
          <Badge dot>
            <CalendarOutlined style={{ fontSize: 16 }} />
          </Badge>
        </Button>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: (date: string) => new Date(date).toLocaleDateString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space>
          <Button type="primary" onClick={() => handleViewApplications(record.id)}>
            查看申请
          </Button>
          <Button 
            type="primary" 
            onClick={() => {
              setSelectedClubId(record.id);
              setSelectedClubName(record.name);
              setIsCreateModalVisible(true);
            }}
          >
            创建活动
          </Button>
        </Space>
      ),
    },
  ];

  const applicationColumns: ColumnsType<Application> = [
    {
      title: '学号',
      dataIndex: 'student_no',
      key: 'student_no',
      width: 120,
    },
    {
      title: '申请人姓名',
      dataIndex: 'student_name',
      key: 'student_name',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      width: 80,
    },
    {
      title: '申请时间',
      dataIndex: 'apply_time',
      key: 'apply_time',
      width: 150,
      render: (date: string) => new Date(date).toLocaleDateString(),
    },
    {
      title: '处理',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space>
          <Button 
            type="primary" 
            onClick={() => handleApplicationStatus(record.id, 'approved')}
          >
            通过
          </Button>
          <Button 
            danger 
            onClick={() => handleApplicationStatus(record.id, 'rejected')}
          >
            拒绝
          </Button>
        </Space>
      ),
    },
  ];

  const memberColumns: ColumnsType<Member> = [
    {
      title: '学号',
      dataIndex: 'student_no',
      key: 'student_no',
      width: 120,
    },
    {
      title: '姓名',
      dataIndex: 'student_name',
      key: 'student_name',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      width: 80,
    },
    {
      title: '加入时间',
      dataIndex: 'approve_time',
      key: 'approve_time',
      width: 150,
      render: (date: string) => new Date(date).toLocaleDateString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Popconfirm
          title={`确定要将 "${record.student_name}" 踢出社团吗？`}
          okText="踢出"
          okType="danger"
          cancelText="取消"
          onConfirm={() => handleRemoveMember(record.student_id, selectedClubId!)}
        >
          <Button 
            type="link" 
            danger 
            size="small"
          >
            踢出社团
          </Button>
        </Popconfirm>
      ),
    },
  ];

  const ActivityListModal = () => {
    return (
      <Modal
        title={`${selectedClubName} - 社团活动`}
        open={isActivityModalVisible}
        onCancel={() => setIsActivityModalVisible(false)}
        footer={null}
        width={800}
      >
        <List
          dataSource={activities}
          renderItem={(activity) => (
            <List.Item
              actions={[
                <Button 
                  type="primary" 
                  onClick={() => {
                    setSelectedActivity(activity);
                    setIsUpdateModalVisible(true);
                  }}
                >
                  更新活动
                </Button>,
                <Button
                  onClick={() => {
                    fetchRegisteredStudents(activity.id);
                    setIsRegisteredStudentsModalVisible(true);
                  }}
                >
                  查看报名
                </Button>,
                <Button 
                  onClick={() => generateSignInCode(activity.id)}
                >
                  生成签到码
                </Button>
              ]}
            >
              <List.Item.Meta
                title={activity.title}
                description={
                  <div>
                    <p>类型：{activity.type}</p>
                    <p>地点：{activity.location}</p>
                    <p>开始时间：{new Date(activity.start_time).toLocaleString()}</p>
                    <p>结束时间：{new Date(activity.end_time).toLocaleString()}</p>
                    <p>报名截止时间：{new Date(activity.signup_deadline).toLocaleString()}</p>
                    <p>最大参与人数：{activity.max_participants}</p>
                    <p>活动积分：{activity.points}</p>
                    {activitySignInCodes[activity.id] && (
                      <p style={{ fontWeight: 'bold', color: 'green' }}>
                        签到码: {activitySignInCodes[activity.id]}
                      </p>
                    )}
                  </div>
                }
              />
            </List.Item>
          )}
        />
      </Modal>
    );
  };

  const UpdateActivityModal = () => {
    const [form] = Form.useForm();

    useEffect(() => {
      if (selectedActivity) {
        form.setFieldsValue({
          title: selectedActivity.title,
          type: selectedActivity.type,
          description: selectedActivity.description,
          location: selectedActivity.location,
          start_time: moment(selectedActivity.start_time),
          end_time: moment(selectedActivity.end_time),
          points: selectedActivity.points,
          max_participants: selectedActivity.max_participants,
          signup_deadline: moment(selectedActivity.signup_deadline)
        });
      }
    }, [selectedActivity, form]);

    return (
      <Modal
        title="更新活动"
        open={isUpdateModalVisible}
        onCancel={() => setIsUpdateModalVisible(false)}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleUpdateActivity}
        >
          <Form.Item
            name="title"
            label="活动标题"
            rules={[{ required: true, message: '请输入活动标题' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="type"
            label="活动类型"
            rules={[{ required: true, message: '请输入活动类型' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="description"
            label="活动描述"
            rules={[{ required: true, message: '请输入活动描述' }]}
          >
            <Input.TextArea />
          </Form.Item>
          <Form.Item
            name="location"
            label="活动地点"
            rules={[{ required: true, message: '请输入活动地点' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="start_time"
            label="开始时间"
            rules={[{ required: true, message: '请选择开始时间' }]}
          >
            <DatePicker showTime />
          </Form.Item>
          <Form.Item
            name="end_time"
            label="结束时间"
            rules={[{ required: true, message: '请选择结束时间' }]}
          >
            <DatePicker showTime />
          </Form.Item>
          <Form.Item
            name="points"
            label="活动积分"
            rules={[{ required: true, message: '请输入活动积分' }]}
          >
            <InputNumber min={0} />
          </Form.Item>
          <Form.Item
            name="max_participants"
            label="最大参与人数"
            rules={[{ required: true, message: '请输入最大参与人数' }]}
          >
            <InputNumber min={1} />
          </Form.Item>
          <Form.Item
            name="signup_deadline"
            label="报名截止时间"
            rules={[{ required: true, message: '请选择报名截止时间' }]}
          >
            <DatePicker showTime />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              更新
            </Button>
            <Button 
              style={{ marginLeft: 8 }} 
              onClick={() => setIsUpdateModalVisible(false)}
            >
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    );
  };

  const CreateActivityModal = () => {
    const [form] = Form.useForm();

    const validateTime = (_: any, value: any) => {
      if (!value) {
        return Promise.reject('请选择时间');
      }
      return Promise.resolve();
    };

    return (
      <Modal
        title="创建活动"
        open={isCreateModalVisible}
        onCancel={() => setIsCreateModalVisible(false)}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleCreateActivity}
        >
          <Form.Item
            name="title"
            label="活动标题"
            rules={[{ required: true, message: '请输入活动标题' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="type"
            label="活动类型"
            rules={[{ required: true, message: '请输入活动类型' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="description"
            label="活动描述"
            rules={[{ required: true, message: '请输入活动描述' }]}
          >
            <Input.TextArea />
          </Form.Item>
          <Form.Item
            name="location"
            label="活动地点"
            rules={[{ required: true, message: '请输入活动地点' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="start_time"
            label="开始时间"
            rules={[{ required: true, validator: validateTime }]}
          >
            <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
          </Form.Item>
          <Form.Item
            name="end_time"
            label="结束时间"
            rules={[
              { required: true, validator: validateTime },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || !getFieldValue('start_time') || value.isAfter(getFieldValue('start_time'))) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('结束时间必须晚于开始时间'));
                },
              }),
            ]}
          >
            <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
          </Form.Item>
          <Form.Item
            name="points"
            label="活动积分"
            rules={[{ required: true, message: '请输入活动积分' }]}
          >
            <InputNumber min={0} />
          </Form.Item>
          <Form.Item
            name="max_participants"
            label="最大参与人数"
            rules={[{ required: true, message: '请输入最大参与人数' }]}
          >
            <InputNumber min={1} />
          </Form.Item>
          <Form.Item
            name="signup_deadline"
            label="报名截止时间"
            rules={[
              { required: true, validator: validateTime },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || !getFieldValue('start_time') || value.isBefore(getFieldValue('start_time'))) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('报名截止时间必须早于活动开始时间'));
                },
              }),
            ]}
          >
            <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              创建
            </Button>
            <Button 
              style={{ marginLeft: 8 }} 
              onClick={() => setIsCreateModalVisible(false)}
            >
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    );
  };

  const RegisteredStudentsModal = () => {
    const columns: ColumnsType<RegisteredStudent> = [
      {
        title: '学号',
        dataIndex: 'student_no',
        key: 'student_no',
      },
      {
        title: '姓名',
        dataIndex: 'student_name',
        key: 'student_name',
      },
      {
        title: '报名时间',
        dataIndex: 'register_time',
        key: 'register_time',
        render: (date: string) => new Date(date).toLocaleString(),
      },
    ];

    return (
      <Modal
        title={
          <div>
            <div>已报名学生列表</div>
            <div style={{ fontSize: '14px', color: '#666', marginTop: '8px' }}>
              当前报名人数：{registeredStudents.length} 人
              {selectedActivity && (
                <span style={{ marginLeft: '16px' }}>
                  (最大参与人数：{selectedActivity.max_participants} 人)
                </span>
              )}
            </div>
          </div>
        }
        open={isRegisteredStudentsModalVisible}
        onCancel={() => setIsRegisteredStudentsModalVisible(false)}
        footer={null}
        width={800}
      >
        <Table<RegisteredStudent>
          columns={columns}
          dataSource={registeredStudents}
          rowKey="id"
          loading={{
            spinning: registeredStudentsLoading,
            indicator: <LoadingOutlined style={{ fontSize: 24 }} spin />,
          }}
          bordered
          pagination={{
            total: registeredStudents.length,
            pageSize: 10,
            showTotal: (total) => `共 ${total} 条记录`
          }}
        />
      </Modal>
    );
  };

  // 新增 签到码显示模态框
  const SignInCodeModal = () => {
    return (
      <Modal
        title="活动签到码"
        open={signInCodeModalVisible}
        onCancel={() => setSignInCodeModalVisible(false)}
        footer={null}
      >
        <div style={{ textAlign: 'center', fontSize: '24px', fontWeight: 'bold' }}>
          {currentActivitySignInCode}
        </div>
        <p style={{ textAlign: 'center', marginTop: '16px' }}>请将此签到码告知活动参与者。</p>
      </Modal>
    );
  };

  useEffect(() => {
    fetchClubs();
  }, []);

  useEffect(() => {
    if (selectedClubId) {
      fetchActivities(selectedClubId);
    }
  }, [selectedClubId]);

  return (
    <Card 
      title="我的管理" 
      variant="outlined"
      extra={
        <Button type="primary" onClick={fetchClubs} loading={loading}>
          刷新
        </Button>
      }
    >
      <Table<Club>
        columns={clubColumns}
        dataSource={clubs}
        rowKey="id"
        loading={{
          spinning: loading,
          indicator: <LoadingOutlined style={{ fontSize: 24 }} spin />,
        }}
        bordered
      />

      <Modal
        title="申请列表"
        open={isApplicationModalVisible}
        onCancel={() => setIsApplicationModalVisible(false)}
        footer={null}
        width={800}
      >
        <Table<Application>
          columns={applicationColumns}
          dataSource={applications}
          rowKey="id"
          loading={{
            spinning: applicationsLoading,
            indicator: <LoadingOutlined style={{ fontSize: 24 }} spin />,
          }}
          bordered
        />
      </Modal>

      <Modal
        title={`${selectedClubName} - 成员列表`}
        open={isMembersModalVisible}
        onCancel={() => setIsMembersModalVisible(false)}
        footer={null}
        width={800}
      >
        <Table<Member>
          columns={memberColumns}
          dataSource={members}
          rowKey="id"
          loading={{
            spinning: membersLoading,
            indicator: <LoadingOutlined style={{ fontSize: 24 }} spin />,
          }}
          bordered
        />
      </Modal>

      <ActivityListModal />
      <UpdateActivityModal />
      <CreateActivityModal />
      <RegisteredStudentsModal />
      <SignInCodeModal />
    </Card>
  );
};

export default ManageClub;
